package com.lkm.app_ui.m.Imple.order_0;

import android.os.SystemClock;

import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.javatool.CollectionHelp;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.event.OnWeightInfoChangeEvent;



 abstract class OnValueChanger {









    private int delayTime;

    private SteelyardDataModule dataManager;

    public OnValueChanger(SteelyardDataModule dataManager) {
        this.dataManager = dataManager;
    }



    public void start(int delayTime){
        this.delayTime = delayTime;
        able(true);
    }
    public void stop(){
        able(false);
    }
    
    private boolean hasable = false;
    private void able(boolean able){
        hasable = able;
        if (able) {
            if (autoNext == null) {
                reOnWeightInfoChangeEvent();
            }
        } else {
            if (autoNext != null) {
                LinkBus.unregisterReceiver(autoNext);
                autoNext = null;
            }
        }
    }
    private ObserverAutoNext autoNext;
    
    private void reOnWeightInfoChangeEvent() {
        LinkBus.registerReceiver(autoNext = new ObserverAutoNext<OnWeightInfoChangeEvent>() {
            @Override
            public Class<OnWeightInfoChangeEvent> getBusEventClass() {
                return OnWeightInfoChangeEvent.class;
            }

            float preUnitPrice = -1;
            long preChangeTime = -1;

            
            boolean isCurUnitPriceSave = true;

            @Override
            public void onReceiver(OnWeightInfoChangeEvent data) {
                if(!hasable)return;
//                P.p("=== "+Thread.currentThread().getName());

                

                float unitPrice = getValue(data);

                if (preUnitPrice == -1) {
                    preUnitPrice = unitPrice;
                }

                if (preUnitPrice == unitPrice) {
                    
                    if ((!isCurUnitPriceSave) && preChangeTime != -1 && SystemClock.uptimeMillis() - preChangeTime >= delayTime) {

                        String steelyardMac = data.getSteelyardMac();
                        
                        if (CollectionHelp.isEmpty(dataManager.getGoodEntities(steelyardMac))) {
                            isCurUnitPriceSave = true;
                            requestSaveOrder(steelyardMac);
                        }






                    }

                } else {

                    isCurUnitPriceSave = false;

                    preUnitPrice = unitPrice;
                    preChangeTime = SystemClock.uptimeMillis();
                }
            }


        });
    }

    protected abstract void requestSaveOrder(String steelyardMac);
    protected abstract float getValue(OnWeightInfoChangeEvent data);
}
